package cn.pzhu.javaee.webapp.context;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.sql.DataSource;
import javax.xml.ws.WebServiceException;

public class WebAppContext {
	public final static String WEBAPPCONTEXT_NAME="WebAppContext";
	public final static String BASE_PATH_NAME="base_path";
	private static WebAppContext _context=null;	
	private DataSource dataSource=null;
	private ServletContext servletContext=null;
	private String basePath="";
	private Map<String,Object> mapContainer=new HashMap<String, Object>();
	private WebAppContext(){
		
	}
	public static WebAppContext getWebAppContext(){
		if(_context==null)_context=new WebAppContext();
		return _context;
	}
	public static WebAppContext getWebAppContext(ServletContext servletContext){
		Object context=servletContext.getAttribute(WEBAPPCONTEXT_NAME);
		if(context==null||!(context instanceof WebAppContext)){
			throw new WebServiceException("Not regitster WebAppContext");
		}
		return (WebAppContext)context;
	}
	
	public void regsiter(ServletContext servletContext){
		this.servletContext=servletContext;
		this.servletContext.setAttribute(WEBAPPCONTEXT_NAME, this);
	}
	public void setDataSource(DataSource ds){
		this.dataSource=ds;
	}	
	
	public DataSource getDataSource(){
		if(this.dataSource==null)throw new WebServiceException("datasoure is not set.");
		return this.dataSource;
	}
	
	
	public String getBasePath() {
		return basePath;
	}
	public void setBasePath(String basePath) {		
		this.basePath = basePath;
		this.servletContext.setAttribute(BASE_PATH_NAME, this.basePath);
	}
	public <T extends Object> WebAppContext setAttribute(String name,T obj){
		this.mapContainer.put(name, obj);
		return this;
	}
	
	@SuppressWarnings("unchecked")
	public <T extends Object> T getAttribute(String name){
		Object obj=this.mapContainer.get(name);
		if(obj!=null){
			return (T)obj;
		}
		return null;
	}
	
}
